﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System;
using LuaFramework;
using DG.Tweening;

public class VoiceRecord : MonoBehaviour
{
    void Awake()
    {
        haveMicrophone = false;
        isStart = false;
        timeMax = 15f;
    }
    private AudioClip recordedClip;
    private bool haveMicrophone;
    private float timeMax;
    private bool isStart;
    public void StartRecord()
    {
        isStart = true;
        Util.CallMethod("SGGameDeskCtrl", "OnRecordStart");
        if (Microphone.devices.Length <= 0) haveMicrophone = false;
        else haveMicrophone = true;
        recordedClip = Microphone.Start(null, false, 16, 10000);
    }
    public void StopRecord()
    {
        if (!isStart) return;
        isStart = false;
        Util.CallMethod("SGGameDeskCtrl", "OnRecordStop");
        if (!haveMicrophone) return;
        var position = Microphone.GetPosition(null);
        var soundData = new float[recordedClip.samples * recordedClip.channels];
        recordedClip.GetData(soundData, 0);
        //Create shortened array for the data that was used for recording
        var newData = new float[position * recordedClip.channels];
        //Copy the used samples to a new array
        for (var i = 0; i < newData.Length; i++) newData[i] = soundData[i];
        try
        {
            recordedClip = AudioClip.Create(recordedClip.name,
            position,
            recordedClip.channels,
            recordedClip.frequency,
            false);
            recordedClip.SetData(newData, 0);
            Microphone.End(null);
            string recordedAudioPath;
            var data = WavUtility.FromAudioClip(recordedClip, out recordedAudioPath, false);
            string str = RecordHttp.Send(data);
            Util.CallMethod("SGGameDeskCtrl", "OnRecordSuccess", str);
            //msgMgr.SendMsg6_46(Tools.ConvertChatContentToInt(ChatContent.Voice), str);
        }
        catch (Exception)
        {
            Debug.Log("语音报错，try》catch》");
            return;
        }
    }
}